<template>
  <div style="margin-top: 5px">
    <div class="alert">
      <span><icon-exclamation-circle /></span>
      <span>所有按店铺隔离数据的功能，按此处分配的店铺在加上店铺设置的店员和店长来展示数据。</span>
    </div>
    <FilterTable :filterItem="filterItem" :isReset="false" :is-show-tag="false" @search="searchByVal" />
    <a-space>
      <a-switch v-model="detailInfo.shopConfig.isAuthAll" @change="handleSwitchChange">
        <template #checked> 开 </template>
        <template #unchecked> 关 </template>
      </a-switch>
      <div>授权所有店铺<span style="color: #7f7f7f">（开启授权所有将不能进行单个授权，且之后新增店铺自动在授权范围内）</span></div>
    </a-space>
    <div class="table-space mt10">
      <div class="left">
        <div class="top">
          <div>未授权店铺</div>
          <div><a-button type="text" @click="matchSetAuth">批量授权</a-button></div>
        </div>
        <div class="bottom">
          <a-table size="mini" class="table-single-line" v-model:selected-keys="selIds" row-key="sellerMarketId" :data="shopList" :virtual-list-props="{ height: 400 }" :pagination="false" :row-selection="rowSelection" :scroll="{ y: 400 }">
            <template #columns>
              <a-table-column title="平台" #cell="{ record }" :width="80">{{ record.platform }}</a-table-column>
              <a-table-column title="店铺" #cell="{ record }" :width="100">
                {{ record.shopName }}
              </a-table-column>
              <a-table-column title="国家" #cell="{ record }" :width="80">{{ record.marketplaceName }}</a-table-column>
              <a-table-column title="状态" #cell="{ record }" :width="60">{{ record.status == 1 ? '启用' : '禁用' }}</a-table-column>
              <a-table-column title="操作" #cell="{ record }" :width="40">
                <a-button type="text" @click="singleAuth(record)">授权</a-button>
              </a-table-column>
            </template>
          </a-table>
        </div>
      </div>
      <div class="right">
        <div class="top">
          <div>已授权店铺</div>
          <div><a-button type="text" @click="cancelAuth('match')"> 批量取消授权</a-button></div>
        </div>
        <div class="bottom">
          <a-table size="mini" class="table-single-line" v-model:selected-keys="noSelIds" row-key="sellerMarketId" :data="selShoplist" :virtual-list-props="{ height: 400 }" :pagination="false" :row-selection="rowSelection" :scroll="{ y: 400 }">
            <template #columns>
              <a-table-column title="平台" #cell="{ record }" :width="80">{{ record.platform }}</a-table-column>
              <a-table-column title="店铺" #cell="{ record }" :width="100">
                {{ record.shopName }}
              </a-table-column>
              <a-table-column title="国家" #cell="{ record }" :width="80">{{ record.marketplaceName }}</a-table-column>
              <a-table-column title="状态" #cell="{ record }" :width="60">{{ record.status == 1 ? '启用' : '禁用' }}</a-table-column>
              <a-table-column title="操作" #cell="{ record }" :width="70">
                <a-button type="text" @click="cancelAuth('single', record)">取消授权</a-button>
              </a-table-column>
            </template>
          </a-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, watch, nextTick } from 'vue'
  import { findShopMarketByNoPermission, saveOrUpdateDataPermissonGroup } from '@/api/system'
  import FilterTable from '@/components/TableFilter.vue'
  import _ from 'lodash-es'
  import { Message } from '@arco-design/web-vue'
  export default defineComponent({
    components: { FilterTable },
    props: ['info', 'refresh'],
    setup(props: any, { emit }) {
      const data: any = reactive({
        filterItem: [
          {
            key: 'shopName',
            label: '店铺名称',
            value: ref(),
            type: 'input_search',
            tabType: 'shop',
            width: 200,
          },
          {
            key: 'sellerId',
            label: 'SellerID',
            value: ref(),
            type: 'input_search',
            tabType: 'shop',
            width: 200,
          },
          {
            key: 'masterName',
            label: '店长',
            value: ref(),
            type: 'input_search',
            tabType: 'shop',
            width: 200,
          },
        ],
        selShoplist: [],
        rowSelection: {
          type: 'checkbox',
          showCheckedAll: true,
          onlyCurrent: false,
        },
        selIds: [],
        noSelIds: [],
        detailInfo: {},
        shopList: [],
      })

      const matchSetAuth = () => {
        if (!data.selIds[0]) {
          return Message.error('请选择需要授权的店铺')
        }
        data.detailInfo.shopConfig.sellerMarketIdList = [...data.selIds, ...data.detailInfo.shopConfig.sellerMarketIdList]

        savePer()
      }

      const cancelAuth = async (type: string, item?: any) => {
        props.refresh()
        if (type == 'match' && !data.noSelIds[0]) {
          return Message.error('请选择需要取消授权的店铺')
        }
        let arr1 = new Set(data.detailInfo.shopConfig.sellerMarketIdList)
        let arr2 = type == 'match' ? new Set(data.noSelIds) : new Set([item.sellerMarketId])
        const differenceSet = new Set([...arr1].filter((x) => !arr2.has(x)))
        data.detailInfo.shopConfig.sellerMarketIdList = Array.from(differenceSet)
        savePer()
      }

      const singleAuth = (item: any) => {
        data.detailInfo.shopConfig.sellerMarketIdList = [item.sellerMarketId, ...data.detailInfo.shopConfig.sellerMarketIdList]
        savePer()
      }

      const getShopMarketList = async (type?: string) => {
        let params = {
          ...data.searchValue,
          share: false,
        }
        const res: any = await findShopMarketByNoPermission(params)
        data.shopList = res?.data || []
        if (type) {
          let arr = data.detailInfo.shopConfig?.sellerMarketIdList || []
          data.selShoplist = []
          arr.forEach((e: any) => {
            let item: any = data.shopList.find((el: any) => e == el.sellerMarketId)
            if (item) data.selShoplist.push(item)
          })
        }
      }

      const searchByVal = (info: any) => {
        data.searchValue = {}
        data.searchValue = info
        getShopMarketList('1')
      }

      const initData = (item: any) => {
        data.detailInfo = _.cloneDeep(item)
        data.selShoplist = []
        if (!data.detailInfo.shopConfig) {
          let obj = {
            authAll: false,
            sellerMarketIdList: [],
          }
          data.detailInfo.shopConfig = obj
        } else {
          let arr = data.detailInfo.shopConfig?.sellerMarketIdList || []
          arr.forEach((e: any) => {
            let item: any = data.shopList.find((el: any) => e == el.sellerMarketId)
            if (item) data.selShoplist.push(item)
          })
        }
      }

      const handleSwitchChange = (val: boolean) => {
        savePer()
      }

      const savePer = async () => {
        let ids = data.detailInfo.shopConfig.sellerMarketIdList
        let arr = Array.from(new Set(ids))
        data.detailInfo.shopConfig.sellerMarketIdList = arr
        let shopIdList: any = []
        let sellerMarketIdList = data.detailInfo.shopConfig.sellerMarketIdList
        sellerMarketIdList.forEach((e: any) => {
          let item: any = data.shopList.find((el: any) => e == el.sellerMarketId)
          if (item) shopIdList.push(item.id)
        })
        data.detailInfo.shopConfig.shopIdList = shopIdList
        const res: any = await saveOrUpdateDataPermissonGroup([data.detailInfo])
        if (res) {
          Message.success('授权成功')
          props.refresh()
        }
        data.selIds = []
        data.noSelIds = []
      }

      watch(
        () => props.info,
        (val) => {
          initData(val)
        },
        { deep: true, immediate: true }
      )
      getShopMarketList('1')
      return {
        ...(toRefs(data) as any),
        matchSetAuth,
        searchByVal,
        handleSwitchChange,
        singleAuth,
        cancelAuth,
      }
    },
  })
</script>

<style lang="less" scoped>
  .alert {
    color: red;
    margin-bottom: 5px;
  }

  .table-space {
    width: 100%;
    display: flex;

    .left,
    .right {
      .top {
        padding: 0 10px;
        display: flex;
        justify-content: space-between;
        background-color: #f2f2f2;
        height: 40px;
        line-height: 40px;
        border-bottom: 1px solid #d7d7d7;
      }
      .bottom {
        padding: 3px;
        box-sizing: border-box;
      }
    }

    .left {
      width: 50%;
      border: 1px solid #d7d7d7;
      margin-right: 10px;
    }
    .right {
      flex: 1;
      border: 1px solid #d7d7d7;
    }
  }
</style>
